package com.ldy.frame; /**
 * Created by MacBook Pro on 2017/11/22.
 */

import org.json.*;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Iterator;


public class Server {
    public static final int PORT = 12345;//监听的端口号

    public static void main(String[] args) {
        Server server =new Server();
        server.init();

    }
    public void init()
    {
        ServerSocket serversocket =null;
        Socket socket =null;
        try{
            serversocket = new ServerSocket(PORT);
            socket =serversocket.accept();
            new HandlerThread(socket);
        }catch (Exception e)
        {
            System.out.println("服务器异常:"+e.getMessage());
        }
    }
    private  class HandlerThread implements Runnable{
        private Socket socket;

        public HandlerThread(Socket client)
        {
            socket =client;
            new Thread(this).start();
        }
        public void run()
        {
            //创建输入输出流
            DataInputStream inputstream=null;
            DataOutputStream outputstream=null;
            String strInputstram="";
            String key,value;
            //从InputStream中获取数据
            try {
                inputstream = new DataInputStream(socket.getInputStream());
                ByteArrayOutputStream baos =new ByteArrayOutputStream();
                byte[] by = new byte[2048];
                int n;
                //通过input
                while((n=inputstream.read(by))!=-1){
                    baos.write(by,0,n);
                }
                strInputstram = new String(baos.toByteArray());
//                System.out.println("接受到的数据长度为："+strInputstream);
                socket.shutdownInput();
//                inputStream.close();
                baos.close();

                //客户端处理数据
                //将socket接收到的数据还原为JSONobject
                JSONObject json = new JSONObject(strInputstram);
                Iterator iterator =json.keys();
                while (iterator.hasNext())
                {
                    key =(String)iterator.next();
                    value =json.getString(key);
                    System.out.println("Key is "+key+". Value is "+ value+ " .");
                }
            }catch (Exception e)
            {
                System.out.println("服务器run异常："+e.getMessage());
            }
        }
    }

}
